//
//  NetEngine.swift
//  example10014
//
//  Created by kazarus on 7/19/16.
//  Copyright © 2016 kazarus. All rights reserved.
//

import Foundation

enum THttpMethod: String {
    case GET = "GET"
    case POST = "POST"
    case PUT = "PUT"
    case DELETE = "DELETE"
}

class TNetClient:NSObject,URLSessionDelegate{
    
    private let baseURL: String
    
    /*
    func URLSession(session: URLSession, didReceiveChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        
        if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
            
            let credential = URLCredential(forTrust: challenge.protectionSpace.serverTrust!)
            completionHandler(URLSession.AuthChallengeDisposition.UseCredential, credential)
            
        }
        
    }
    */
    
    public init(baseURL: String) {
        self.baseURL = baseURL
    }
    
    public func run(method:THttpMethod,target:String,params: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>(),completionHandler: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void){
        
        let session = URLSession.shared
        
        
        
        //var request = NSMutableURLRequest(url:URL(string:target)!)
        var request = URLRequest(url:URL(string:target)!)
        request.httpMethod=method.rawValue
        
        
        if params.count>0{
        } else{
        }
        


        /*
        let task = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
            callback(data,response,error)
        })
        */
        let task = session.dataTask(with: request){
            (data,response,error) in
            DispatchQueue.main.async {
                completionHandler(data,response,error)
            }
        }
        
        task.resume()
    }
    
    public func mul(method:THttpMethod,target:String,params: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>(),completionHandler: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void){
        
        //#let session = URLSession.shared
        let session = URLSession(configuration:URLSession.shared.configuration,delegate:self,delegateQueue:URLSession.shared.delegateQueue)
        
        //#let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(String.Encoding.utf8.rawValue))
        //#print(charset as Any)
        
        var request = URLRequest(url:URL(string:self.baseURL+target)!)
        request.httpMethod=method.rawValue;

        //var request = URLRequest(url:URL(string:target)!)
        //#request.httpMethod=method.rawValue
        //request.setValue("application/x-www-form-urlencoded; charset=\(charset)", forHTTPHeaderField: "Content-Type")
        
        
        var para = ""
        for item in params {
            para = item.key+"="+(item.value as! String)
        }
        print(para)
        
        request.httpBody = para.data(using: String.Encoding.utf8)//; charset=\(charset)
        request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        
        //#request.addValue("application/json;text/html", forHTTPHeaderField: "Content-Type")
        //#request.addValue("application/json", forHTTPHeaderField: "Accept")
        //#request.addValue("\(paramsData.count)", forHTTPHeaderField: "Content-Length")
        
        //#request.addValue("192.168.0.3", forHTTPHeaderField: "Host")
        
        
        
        
        let task = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
            DispatchQueue.main.async {
                completionHandler(data,response,error)
            }
        })
        
        task.resume()
        
    }
    
    static func joinPath(with path:String)->String{
        let result = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]+"/"+path
        return result
    }
    
    
    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
    }
    

}
